package com.wenhao.leetcode.medium;

import java.util.concurrent.Semaphore;
import java.util.function.IntConsumer;

class ZeroEvenOdd {
    private int n;
    private volatile int i = 1;
    private Semaphore zero = new Semaphore(1);
    private Semaphore even = new Semaphore(0);
    private Semaphore odd = new Semaphore(0);

    public ZeroEvenOdd(int n) {
        this.n = n;
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        while (i < n) {
            zero.acquire();
            printNumber.accept(0);
            if ((i & 1) == 1) {
                odd.release();
            } else {
                even.release();
            }
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        while (i <= n) {
            if ((i & 1) == 0) {
                even.acquire();
                printNumber.accept(i++);
                zero.release();
            }
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        while (i <= n) {
            if ((i & 1) == 1) {
                odd.acquire();
                printNumber.accept(i++);
                zero.release();
            }
        }
    }
}
